package com.tjsinfo.tjsoa.system.action;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ResourceBundle;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.tjsinfo.tjsoa.fileDocument.bo.IFileDocumentFileBo;
import com.tjsinfo.tjsoa.fileDocument.vo.FileDocumentFile;

public class IOAction extends Action {
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		String url = "error";
		// TODO Auto-generated method stub
		try {
			//String url = request.getSession().getServletContext().getRealPath("/")+ "uploadCachet\\";
			
			//String path = new String(request.getParameter("path").getBytes("ISO8859-1"), "UTF-8");
			String fileName=request.getParameter("fileName");
			ResourceBundle bundle = ResourceBundle.getBundle("com.tjsinfo.tjsoa.system.properties.systemResource_zh_CN");
			String path  = bundle.getString("system.kuaijie");
			
			File file = new File(path+fileName); 
			
			String filename = file.getName();
			// 取得文件的扩展名ext
			String ext = filename.substring(filename.lastIndexOf(".") + 1)
					.toUpperCase();

			InputStream fis = new BufferedInputStream(new FileInputStream(path+'\\'+fileName));
			byte[] buffer = new byte[fis.available()];
			fis.read(buffer);
			fis.close();
			
			
			response.reset();
			response.addHeader("Content-Disposition", "attachment;filename="
					+ new String(filename.getBytes("GBK"),"iso-8859-1"));
			response.addHeader("Content-Length", "" + file.length()); // 设置返回的文件类型
			OutputStream toClient = new BufferedOutputStream(response
					.getOutputStream()); // 得到向客户端输出二进制数据的对象
			// 根据扩展名声称客户端浏览器mime类型
			if (ext.equals("DOC"))
				response.setContentType("application/msword");
			else
				response.setContentType("application/octet-stream"); // 设置返回的文件类型
			toClient.write(buffer); // 输出数据
			toClient.flush();
			toClient.close();
			url = "ok";
		} catch (IOException ex) {
			request.setAttribute("returnSting", "服务器忙，请稍后下载！");
			return mapping.findForward("error");
		} catch(NullPointerException ex){
			return null;
		} catch (Exception ex){
			request.setAttribute("returnSting", "服务器忙，请稍后下载！");
			return mapping.findForward("error");
		}
		if ("ok".equals(url)) {
			return null;	
		}else {
			request.setAttribute("returnSting", "服务器忙，请稍后下载！");
			return  mapping.findForward(url);
		}
	}
}
